package configlogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpConfigLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	isExConfigKeyLogic *IsExConfigKeyLogic
}

func NewUpConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpConfigLogic {
	return &UpConfigLogic{
		ctx:                ctx,
		svcCtx:             svcCtx,
		Logger:             logx.WithContext(ctx),
		isExConfigKeyLogic: NewIsExConfigKeyLogic(ctx, svcCtx),
	}
}

func (l *UpConfigLogic) UpConfig(in *syspb.UpConfigReq) (*syspb.UpConfigResp, error) {
	config := in.GetParams()
	if config == nil || config.GetConfigId() == 0 || config.GetConfigName() == "" ||
		config.GetConfigKey() == "" || config.GetConfigValue() == "" || config.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新参数配置失败：参数缺失"),
			tool.GetErrMsgFormat("update config"), "params is not existed", in)
	}

	// 校验参数键名重复
	resp, err := l.isExConfigKeyLogic.IsExConfigKey(&syspb.IsExConfigKeyReq{
		ConfigKey: config.GetConfigKey(),
		IsNotId:   config.GetConfigId(),
	})
	if err != nil {
		return nil, err
	}
	if resp.GetIsExist() {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新参数配置失败：参数键名重复"),
			tool.GetErrMsgFormat("update config"), "config key is existed", in)
	}

	// 转换数据
	one, err := l.svcCtx.SysConfigModel.FindOne(l.ctx, config.GetConfigId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update config"), err, in)
	}
	one.ConfigName = config.GetConfigName()
	one.ConfigKey = config.GetConfigKey()
	one.ConfigValue = config.GetConfigValue()
	one.ConfigType = config.GetConfigType()
	one.Remark = config.GetRemark()
	one.UpdateUser = config.GetUpdateUser()

	// 更新数据
	err = l.svcCtx.SysConfigModel.UpdateEx(l.ctx, nil, one)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update config"), err, in)
	}

	return &syspb.UpConfigResp{}, nil
}
